# from urllib.parse import quote
import json
from urllib.parse import quote
from lxml import html
import cssutils
import requests

from src import utils
from src.verification_captcha import VerificationCaptcha


def get_css_properties(sheet):
    # 创建一个字典来保存属性
    display_list = []
    # 遍历所有的规则
    for rule in sheet:
        if rule.type == rule.STYLE_RULE:
            for property in rule.style:
                if property.name == 'display' and property.value == 'block':
                    display_list.append(rule.selectorText)

    return display_list


def get_form_index(tree, displayList):
    for i in range(5):
        VisaType = tree.xpath('//input[@id="AppointmentDate' + str(i + 1) + '"]/..')[0].get('class')
        for tt in VisaType.split(' '):
            if '.' + tt in displayList:
                return str(i + 1)


class AppointmentTicket:
    def __init__(self, html_content, appointmentDate, appointmentSlot, cookies, ImageId):
        self.tree = html.fromstring(html_content)
        self.appointmentDate = appointmentDate
        self.appointmentSlot = appointmentSlot
        self.cookies = cookies
        self.imageId = ImageId

    def get_captcha_data(self):
        verifi = VerificationCaptcha('/CHN/NewCaptcha/GenerateCaptcha', cookies=self.cookies, is_login=False)
        captcha_data = verifi.get_captcha_data()
        return captcha_data

    def create(self):
        captcha_data = self.get_captcha_data()
        # print(captcha_data)
        style_tags = self.tree.xpath('//style')
        stylesheet = cssutils.parseString(style_tags[1].text)
        displayList = get_css_properties(stylesheet)
        index = get_form_index(self.tree, displayList)

        form = self.tree.xpath('//form')[0]
        # 获取表单数据
        form_data = {}
        for input_ele in form.xpath('.//input'):
            input_name = input_ele.get('name')
            input_value = input_ele.get('value')
            if input_name:
                form_data[input_name] = input_value or ''

        form_data['AppointmentDate' + index] = self.appointmentDate
        form_data['AppointmentSlot' + index] = self.appointmentSlot
        form_data['ImageId'] = self.imageId
        form_data['AppointmentDetailsList'] = '%5B%5D'
        form_data['CaptchaData'] = captcha_data
        # form_data['EmailVerified'] = True
        form_data['ServerAppointmentDate'] = self.appointmentDate
        form_data['X-Requested-With'] = 'XMLHttpRequest'
        # form_data['EmailVerificationCode'] = ''
        # https://spain.blscn.cn/CHN/query/getfile?fileid=77705f0e-7d13-43b6-9daa-a8b2e71d4706

        url = 'https://spain.blscn.cn/CHN/BLSAppointment/ManageAppointment'
        headers = utils.get_headers()
        res = requests.post(url, headers=headers, cookies=self.cookies, data=form_data)
        print(res.status_code)
        print(res.json())

    def confirm(self):
        applicantsDetailsList = [
            {
                "ApplicantSerialNo": "1", "FirstName": "zheng", "SurName": "zheng", "LastName": "changjun",
                "ServerDateOfBirth": "1990-03-25", "PlaceOfBirth": "北京",
                "CountryOfBirthId": "5e44cd63-68f0-41f2-b708-0eb3bf9f4a72",
                "NationalityId": "5e44cd63-68f0-41f2-b708-0eb3bf9f4a72",
                "NationalityAtBirthId": "5e44cd63-68f0-41f2-b708-0eb3bf9f4a72",
                "GenderId": "2a299467-0281-4efc-bd69-0cba402d6b26",
                "MaritalStatusId": "23c3d9ec-f504-4109-89b5-804189ecb4c1",
                "IsMinor": False, "MinorParentSurname": "", "MinorParentFirstName": "", "MinorParentLastName": "",
                "MinorParentNationalityId": "", "MinorParentAddress": "", "NationalIdentityNumber": "",
                "PassportType": "ea3865a7-edae-4768-8883-3bc9339bdd85", "PassportNo": "2300000000",
                "ServerPassportIssueDate": "2024-03-18", "ServerPassportExpiryDate": "2025-07-05",
                "ServerTravelDate": "2024-03-30", "IssuePlace": "121212121212",
                "IssueCountryId": "5e44cd63-68f0-41f2-b708-0eb3bf9f4a72", "HomeAddressLine1": "",
                "HomeAddressLine2": "",
                "HomeAddressCountryId": "", "HomeAddressState": "", "HomeAddressCity": "", "HomeAddressPostalCode": "",
                "HomeAddressContactNumber": "", "HasOtherResidenceship": False, "OtherResidenceshipPermitNumber": "",
                "EmployerName": "", "EmployerPhone": "", "EmployerAddress": "", "CurrentOccupationId": "",
                "PurposeOfJourneyId": "351336f9-b83c-4eab-9676-756f110b7a78",
                "MemberStateDestinationId": "5e44cd63-68f0-41f2-b708-0eb3bf9f4a72",
                "MemberStateSecondDestinationId": "",
                "MemberStateFirstEntryId": "", "NumberOfEntriesRequested": "", "IntendedStayDuration": "",
                "IsVisaIssuedBefore": False, "PreviousVisaNumber": "", "PreviousVisaIssuedCountryId": "",
                "PreviousFingerPrintStatus": "0", "FinalDestinationIssuedByCountryId": "", "BlsInvitingAuthority": "0",
                "InvitingAuthorityName": "", "InvitingCountryId": "", "InvitingCity": "", "InvitingZipCode": "",
                "InvitingAddress": "", "InvitingEmail": "", "InvitingContactNo": "", "InvitingFaxNo": "",
                "InvitingContactName": "", "InvitingContactSurname": "", "InvitingContactCountryId": "",
                "InvitingContactCity": "", "InvitingContactZipCode": "", "InvitingContactAddress": "",
                "InvitingContactContactNo": "", "InvitingContactEmail": "", "InvitingContactFaxNo": "",
                "CostCoveredById": "",
                "MeansOfSupportId": "", "OtherCitizenSurname": "", "OtherCitizenFirstName": "",
                "OtherCitizenNationalityId": "",
                "OtherCitizenDocumentNumber": "", "OtherCitizenFamilyRelationshipId": "",
                "ParentId": "56f41f5c-f58d-4989-9079-45436a89628e",
                "ApplicantId": "04b8dda3-2a7d-42f8-bb40-0f5ca04f52fc",
                "Id": "04b8dda3-2a7d-42f8-bb40-0f5ca04f52fc"
            }
        ]

        json_str = json.dumps(applicantsDetailsList)

        data = {
            'VisaType': '099a0161-b428-4a10-bb1e-639b7dee4fa0',
            'PreviousFingerPrintStatus_0': 0,
            'BlsInvitingAuthority_0': 0,
            'ScriptData': '',
            'Id': '56f41f5c-f58d-4989-9079-45436a89628e',
            'DataAction': 'Edit',
            'Email': '1248198090%40qq.com',
            'ApplicantsNo': '1',
            'LocationId': '8d780684-1524-4bda-b138-7c71a8591944',
            'Mobile': '18519203764',
            'MobileCountryCode': '%2B86',
            'AppointmentId': '56f41f5c-f58d-4989-9079-45436a89628e',
            'AppointmentFor': 'Individual',
            'ApplicantsDetailsList': quote(json_str),
            'TotalAmount': '',
            'ApplicantPhotoId': '3005f2e1-d2a4-48a8-a46b-c1a7d2f526c1',
            'ImageId': '',
            'AppointmentCategoryId': '5c2e8e01-796d-4347-95ae-0c95a9177b26',
            'AppointmentDate': quote('2024-04-05+00:00:00.000'),
            'SaveState': 'Application',
            'AppointmentNo': '',
            'CaptchaId': 'df7645c1-15a1-4306-affd-3e4c393307ef',
            'MinimumPassportValidityDays': '180',
            'ServerTravelDate': '',
            'RemoveChildren': 'False',
            'VisaTypeCode': 'SCHENGEN_VISA',
            '__RequestVerificationToken': 'CfDJ8ItFsDhqkWRIiWYGIDDs_SOny0gbm2bgiejMBJqDRNxcMM-kut2Elj-JIOmDcUW3aAXQCNW2I35XI0Hs0gBulQq6rXxBrkupeis9JWSEmWTXe7sT8Ioogw1OV1kVzUmRcXZCeNDz47BQgCGUIqi95H4gZw2azNRhjZ90LL0pI7Eo3hbga75sEcA3sZKB1O5TcQ',
            'X-Requested-With': 'XMLHttpRequest'
        }
        headers = utils.get_headers()
        url = 'https://spain.blscn.cn/CHN/BLSAppointment/ManageAppointment'
        res = requests.post(url, headers=headers, cookies=self.cookies, data=data)

    def payment_request(self):
        data = {
            'Id': 'ee2c1641-630a-463a-83f8-b1a4f23906d6',
            'ValueAddedServices': '8b95ae10-9215-49d0-bff1-0b47a5e32b08_1',
            'LivenessDeclarationAccepted': False,
            'PaymentGatewayType': 4
        }
        url = 'https://spain.blscn.cn/CHN/payment/PaymentRequest'
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
            'requestverificationtoken': 'CfDJ8ItFsDhqkWRIiWYGIDDs_SNgxmgfhD56DbAIkFZ2x-G_BLAWvaAWUiYm75m8DKc99fNhW62UTirqnjLTmnY8lDUqmx7f02mRIdVQ38X82gBf_5c6ZRnqE6l3cQfyfDLjet8gqWw1lEhI80wZKU9yeM-2l9iXHuV5EXK5CLm31d8ZYQAOy0V6sgX3j_olXLSJfg',
            'X-Requested-With': 'XMLHttpRequest'
        }
        res = requests.post(url, headers=headers, cookies=self.cookies, data=data)
